package drugdealer.control;

import java.io.IOException;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import drugdealer.data.PacienteDAO;
import drugdealer.exception.UserTypeException;
import drugdealer.model.Paciente;

/**
 * Servlet implementation class CadastraServlet.
 * 
 * When a new user registers her/himself to the system this servlet
 * manages database update with the user's data. 
 * 
 * @author dave
 */
@WebServlet("/cadastroUsuario")
@SuppressWarnings("serial")
public class CadastroServlet extends HttpServlet {

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CadastroServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("CadastroServlet.doPost()");
		
		// Retrieve data from all the fields
		// TODO server side data validation
		String nome = (String) request.getParameter("nome");
		String email = (String) request.getParameter("email");
		String rg = (String) request.getParameter("rg");
		String endereco = (String) request.getParameter("endereco");
		String senha = (String) request.getParameter("senha");

		// Data format is yyyy-mm-dd
		// TODO data format validation and conversion
		Date data = java.sql.Date.valueOf(request.getParameter("data"));

		String url = "";

		// Create a new Paciente Bean
		Paciente p = new Paciente();

		// Fill the Paciente object with retrieved user filled data
		p.setNome(nome);
		p.setEmail(email);
		p.setRG(rg);
		p.setEndereco(endereco);
		p.setSenha(senha);
		p.setAniversario(data);
		
		// Insert the new Paciente into the Database
		int success = 0;

		try {
			success = PacienteDAO.insert(p);
		} catch (UserTypeException e) {
			System.out.println("CadastroServlet.doPost(): Requested user type doesn't exist!"
					+ " => user.getClass(): " + p.getClass());
			e.printStackTrace();
		}
		
		// Set redirect URL
		if (success != 0) {	// if Database update was successful then redirect to login page
			System.out.println("\tUser registration successful");
			url = "/loginRedirect";
		} else {			// otherwise show registration error page
			System.out.println("\tUser registration failed");
				url = "/cadastro/erroCadastro.jsp";
		}
	
		// Redirect
		response.sendRedirect(url);
	}
}
